<template>
    <div class="content">
        <div>
            <h1>学生信息管理系统</h1>
            <form>
                <input type="button" value="新增" @click="$router.push('/addStudent')" />
                <input type="text" placeholder="请输入关键词" v-model="keyWord" />
                <input type="button" value="查询" @click="query" />
            </form>
        </div>

        <div>
            <table>
                <thead>
                    <tr>
                        <th>学生编号</th>
                        <th>学生姓名</th>
                        <th>性别</th>
                        <th>年龄</th>
                        <th>所在班级</th>
                        <th>操作</th>
                    </tr>
                </thead>

                <tbody v-if="students && students.length">
                    <tr v-for="student in students" :key="student.id">
                        <td>{{ student.id }}</td>
                        <td>{{ student.studentName }}</td>
                        <td>{{ student.studentSex }}</td>
                        <td>{{ student.studentAge }}</td>
                        <td>{{ student.className }}</td>
                        <td>
                            <input type="button" value="修改" @click="$router.push(`/updateStudent/${student.id}`)" />
                            <input type="button" value="删除" @click="del(student.id)" />
                        </td>
                    </tr>
                </tbody>

                <tbody v-else>
                    <tr>
                        <td colspan="7">暂无数据</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
// 引用 api
import { ref, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import axios from "axios"

// 后端 api
const api = 'http://localhost:8000/students';

// 学生列表
const students = ref([])

// 周期函数
onMounted(async () => {
    // 查询请求
    const data = await axios.get(api)

    // 获取学生列表
    if (data.data.code === 200) {
        students.value = data.data.data
    }
})

// 关键词
const keyWord = ref('')

// 搜索关键词
async function query() {
    // 请求
    const data = await axios.get(`${api}?keyWord=${keyWord.value}`)

    if (data.data.code === 200) {
        students.value = data.data.data
    }
}

// 删除
async function del(id) {
    if (confirm("确认删除?")) {
        // 删除请求
        const data = await axios.delete(`${api}/${id}`)
        if (data.data.code === 200) {
            const index = students.value.findIndex(item => item.id === id);
            // 删除元素
            students.value.splice(index, 1)
        }
    }
}

</script>

<style scoped>
.content div:first-child {
    padding: 10px;
}
</style>